import schedule
import time
import threading
import logging
from datetime import datetime
from app.models.database import db_manager

logger = logging.getLogger(__name__)

class SchedulerService:
    def __init__(self):
        self.is_running = False
        self.thread = None
    
    def start(self):
        """启动定时任务服务"""
        if self.is_running:
            logger.warning("定时任务服务已在运行")
            return
        
        self.is_running = True
        
        # 设置定时任务
        schedule.every().day.at("02:00").do(self.cleanup_old_data)
        
        # 在后台线程中运行定时任务
        self.thread = threading.Thread(target=self._run_scheduler, daemon=True)
        self.thread.start()
        
        logger.info("定时任务服务已启动")
    
    def stop(self):
        """停止定时任务服务"""
        self.is_running = False
        if self.thread:
            self.thread.join(timeout=5)
        logger.info("定时任务服务已停止")
    
    def _run_scheduler(self):
        """运行定时任务调度器"""
        while self.is_running:
            try:
                schedule.run_pending()
                time.sleep(60)  # 每分钟检查一次
            except Exception as e:
                logger.error(f"定时任务运行错误: {str(e)}")
                time.sleep(60)
    
    def cleanup_old_data(self):
        """清理旧数据任务"""
        try:
            logger.info("开始执行数据清理任务")
            
            # 检查是否启用自动清理
            auto_cleanup = db_manager.get_config('auto_cleanup_enabled')
            if auto_cleanup and auto_cleanup.lower() != 'true':
                logger.info("自动清理功能已禁用")
                return
            
            # 执行数据清理
            result = db_manager.cleanup_old_data()
            logger.info(f"数据清理完成: {result}")
            
        except Exception as e:
            logger.error(f"数据清理任务失败: {str(e)}")
    
    def run_cleanup_now(self):
        """立即执行数据清理"""
        try:
            logger.info("手动执行数据清理")
            result = db_manager.cleanup_old_data()
            logger.info(f"手动数据清理完成: {result}")
            return result
        except Exception as e:
            logger.error(f"手动数据清理失败: {str(e)}")
            raise
    
    def get_next_cleanup_time(self):
        """获取下次清理时间"""
        try:
            cleanup_time = db_manager.get_config('cleanup_time')
            if cleanup_time:
                return cleanup_time
            return "02:00"  # 默认时间
        except Exception as e:
            logger.error(f"获取清理时间失败: {str(e)}")
            return "02:00"
    
    def update_cleanup_schedule(self, time_str: str):
        """更新清理时间"""
        try:
            # 验证时间格式
            datetime.strptime(time_str, "%H:%M")
            
            # 更新配置
            db_manager.update_config('cleanup_time', time_str)
            
            # 重新设置定时任务
            schedule.clear()
            schedule.every().day.at(time_str).do(self.cleanup_old_data)
            
            logger.info(f"清理时间已更新为: {time_str}")
            
        except ValueError:
            raise ValueError("时间格式错误，请使用 HH:MM 格式")
        except Exception as e:
            logger.error(f"更新清理时间失败: {str(e)}")
            raise

# 全局定时任务服务实例
scheduler_service = SchedulerService() 